import { cookiesStorage } from "@/utils/cookie" 

import { defineStore } from 'pinia'

import { getUserInfo } from "@/service/user"

import { getWalletItem, getBankCard, getConfig } from "@/service/login"

import { showFailToast } from 'vant'

import type { UserType } from "./type"

export const useUserStore = defineStore('user', {
  state: (): UserType => {
    return {
      accessToken: undefined,
      basicHeader: 'cmVjeWNsZV9hcHA6dHVva2V5dW4=',
      userInfo: {},
      lang: 'zh-CN',
      wallet: undefined,
      defaultBank: undefined,
      config: undefined,
      isSign: false
    }
  },
  actions: {
    setLang(data: string) { 
      this.lang = data
    },
    logout() {
      this.$reset()
      // this.wallet = {}
      // this.userInfo = {}
     
      // this.jwt = {}
      // this.accessToken = undefined
    },
    setConfig(data: any){
      this.config = data
    },
    setToken(data: string) {
      this.accessToken = data as any
    },
    setUserInfo(data: any) {
      this.userInfo = data
    },
    setWallet(data: any){
      this.wallet = data
    },
    setBank(data: any) {
      this.defaultBank = data
    },
    setSign(data: boolean){
      this.isSign = data
    },
    filterLangArray(data: any[]){
      if(!data || !data.length || !Array.isArray(data)) return ''
      return data.reduce((p, c) => (c.languageType === this.lang ? Object.assign(p, c) : p))
    },
    async loadWallet() {
      try {
        const ret = await getWalletItem({})
        if(!ret.success) return showFailToast(ret.message)
        if(!ret.data) return 
        this.setWallet(ret.data) 
      } catch(err: any){
        throw err
      }
    },
    async loadUserInfo() {
      try{
        const ret = await getUserInfo({}, {
          headers: { Authorization: `Bearer ${this.accessToken}` }
        })
        if(!ret.success) return  showFailToast(ret.message)
        this.setUserInfo(ret.data)
      } catch(err: any){
        throw err
      }
    },
    async loadConfig() {
      try {
        const res = await getConfig({})
        if(!res.success) return 
        const map = res.data.reduce((pre: any, cur: any) => {
          return Object.assign(pre, { [cur.dictCode]: cur.value })
        }, {})
        this.setConfig(map)
      } catch(err){
        throw err
      }
    },
    async loadDefaultBank() {
      try {
        const res = await getBankCard({})
        if(!res.success) return 
        this.setBank(res.data)
      } catch(err){
        throw err
      }
    },
    async userInit() {
      try {
        await this.loadUserInfo()
        await this.loadWallet()
        await this.loadDefaultBank()
        await this.loadConfig()
      } catch(err){
        showFailToast('user init function run error！')
        throw err
      }
    }
  },
  persist: {
    enabled: true, // true 表示开启持久化保存
    strategies: [
      { key: 'basicHeader', storage: cookiesStorage, paths: ['basicHeader']  },
      { key: 'accessToken', storage: cookiesStorage, paths: ['accessToken']  },
      { key: 'wallet', storage: localStorage, paths: ['wallet']  },
      { key: 'defaultBank', storage: localStorage, paths: ['defaultBank']  },
      { key: 'config', storage: localStorage, paths: ['config']  },
      { key: 'lang', storage: localStorage, paths: ['lang'] },
      { key: 'userInfo', storage: localStorage, paths: ['userInfo'] },
    ]
  }
})
